
var t_yb = "<p><table>";
var t_keys = "";//<tr><td style='bakground-color:#dde; width:400px;border:solid 1px #dde;'> &nbsp;</td></tr>";
var t_vals = "<tr><td style='XXXwidth:400px;XXXborder:solid 1px green;'> &nbsp;</td></tr>";
var t_ye = "</table></p>";

function validateNumber(name,num) {
    var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;  
    if (phoneNumberPattern.test(num)) {
        return true;
    }
    sswAlert('ssw_dime', name + ": Phone number is invalid: "+ num);
    return false;
} 

function validateObjectName(nam,name) {
    if (name.length < 6) {
        sswAlert('ssw_dime',nam + " must be at least 6 char long");
        return false;
    }
    var namePattern = /^[A-Z][\w\d-_\.]*$/;  
    if (namePattern.test(name)) {
        return true;
    }
    sswAlert('ssw_dime',nam + " must consist of capital letter followed by letters, dots, numbers, - or _");
    return false;
}

function validateName(nam,n) {
    if (n.length < 1) {
        sswAlert('ssw_dime', nam + " cannot be empty");
        return false;
    }
    var namePattern = /^[A-Z][\w-_\.]*$/;  
    if (namePattern.test(n)) {
        return true;
    }
    sswAlert('ssw_dime',nam + " must consist of capital letter followed by letters, dots, - or _");
    return false;
}

function validatePasswordPair(a,b) {
    if (a == "" && b == "") {
        return true;
    }
    if (a != b) {
        sswAlert('ssw_dime', "Passwords do not match");
        return false
    }
    return validatePassword(a);
} 

function validatePassword(a) {
    if (a != null) {
        if (a.length > 3) {
            return true;
        }
    }
    sswAlert('ssw_dime', "Password must be at least 4 characters long");
    return false
} 

function validateEmail(email) {
    var atpos = email.indexOf("@");
    var atdot = email.lastIndexOf(".");
    if (atpos < 1 || atdot < atpos+2 || atdot+2>=email.length) {
        sswAlert('ssw_dime',"Username must be a valid email address: "+ email);
        return false;
    }
    return true;    
}

function validateStartDate(d) {
    if (d == "") {
        sswAlert('ssw_dime',"Please specify a start date");
        return false;
    }
    var pat = /^(\d{2})[-/.](\d{2})[-/.](\d{2}|\d{4})$/;  
    if (pat.test(d)) {
        return true;
    }
    sswAlert('ssw_dime',"Start date is invalid. Use dd/mm/yyyy");
    return false;
}

function findChecked(l) {
    var c = new Array();
    for (var i=0;i<l.length;i++) {
        if (l[i].checked) {
            c.push(l[i].value);
        }
    }
    return c;    
}

function countChecked(l) {
    var c = 0;
    if (typeof l == "undefined") {
        return 0;
    }
    for (var i=0;i<l.length;i++) {
        if (l[i].checked) {
            c++;
        }
    }
    return c;    
}

function validateAny(nm,val) {
    if (typeof val != "undefined") {
        if (val != "") {
            return true;
        }
    }
    sswAlert('ssw_dime',nm + ": Please make a selection");
    return false;
}

function validateNumDays(ses,pref,alt) {
    var exp = 0;
    var c = findChecked(ses);
    if (c.length != 0) {
        exp = c[0];
    }
    if (exp == 0) {
        sswAlert('ssw_dime',"Number of sessions per week cannot be zero");
        return false;
    }
    var cp  = countChecked(pref);
    var ca  = countChecked(alt);
    if (ca == exp && cp == exp) {
        return true;
    }
    sswAlert('ssw_dime',"Number of sessions per week does not match days checked");
    return false;
}

function validateForm(caller) {
    var f = null;
    if ($(caller).is('form')) {
        f = caller;
    }
    else if ($(caller).is('input')) {
        f = $(caller).parents('form')[0];
    }
    else if ($(caller).is('button')) {
        f = $(caller).parents('form')[0];
    }
    else {
        sswAlert('ssw_dime',"INTERNAL ERROR - Unable to validate form submission");
        return false;
    }
    var ok = validateThisForm(f)
    if (ok) {
        $('div#ssw_submit').html(
            '<button type=button disabled=disabled >Submit</button>'+
            '<input type="submit" value="CONFIRM SUBMISSION" />');
        return true;
    }
    return false;
}

function dumm () {
    return true;
}

function checkIfUnique(claz,name,currid) {
    if (!validateObjectName("Team name",name)) {
        return false;
    }
    var args = new Array();
    var list = processEntitiesFromServer(claz,'list',null,args,false);
    if (list.length == 0) {
        return true;
    }
    for (var i in list) {
        var line = list[i];
        if (line['_name'] === name) {
            if (Number(currid.value) === Number(line['_id'])) {
                continue;
            }
            sswAlert('ssw_dime',"An object of this type with name '" + name + "' already exists");
            return false;
        }
    }
    return true;
}

function validateThisForm(f) {
    var formName = f.name;
    // XXX var f = document.forms[formName];
    if (formName == 'action_CreateTeam') {
        return checkIfUnique('TeamE',f['_name'].value,f['currentid']);
    }
    if (formName == 'request') {
        return (
            validateStartDate(f['_startdate[]'].value) && 
            validateNumDays(f['_sessions[]'],f['_dayr3m1[]'],f['_dayr3m2[]']) &&
            validateAny('Preferred field',f['_fieldr1m1[]'].value) &&
            validateAny('Alternate field',f['_fieldr2m1[]'].value) &&
            validateAny('Preferred time',f['_timer1m2[]'].value) &&
            validateAny('Alternate time',f['_timer2m2[]'].value) 
        );
    }
    if (formName == 'register') {
        return (
            validateEmail(f['_username'].value) &&
            validatePasswordPair(f['_password'].value,f['_cpassword'].value) &&
            validatePassword(f['_password'].value)
        );
    }
    if (formName == 'userinfo') {
        return (
            validateNumber('Home phone',f['_homephone'].value) && 
            validateNumber('Work phone',f['_workphone'].value) && 
            validateNumber('Cell phone',f['_cellphone'].value) &&
            validatePasswordPair(f['_password'].value,f['_cpassword'].value) &&
            validateName('First name',f['_firstname'].value) &&
            validateName('Last name',f['_lastname'].value) 
        );
    }
    return true;
}

function disableForm() {
    $('form').find('input, button, textarea, select').attr('disabled','disabled');
}

function enableForm() {
    $('form').find('input, button, textarea, select').removeAttr('disabled');
}


/*
function buildStringFromFields(list,table,keys) {
    var y = '';
    if (table) {
        y += "<p><table>";
    }
    y += buildRowsStringFromFields(list,table,keys);
    if (table) {
        y += '</table></p>';
    }
    return y;
}

function buildRowsStringFromFields(list,table,keys) {
    y = '';
    var tr1 = '';
    var td1 = '';
    var tr0 = '';
    var td0 = '';
    if (table) {
        tr1 += '<tr>';
        td1 += '<td style="border:solid 1px green;">';
        tr0 += '</tr>';
        td0 += '</td>';// style="border:solid 1px green;">';
    }
    for (var i in list) {        
        y += tr1 + td1;
        var e = list[i];
        if (e == null) {
            e = "?";
        }        
        if (keys) {
            y += i + td0 + td1;
        }
        y += e;
        y += td0 + tr0;
    }
    return y;
}*/

function showNamesAsSelect(list,args) {
    $(args[0]).html(t_yb + t_keys + t_vals + t_ye);
    return showFieldAsSelect(list,args,"_name");
}

function showFieldAsSelect(list,args,field) {
    ////obj1,obj2,list,add,filter,field) {
    //var all = (field == "");
    var y = "<select style='width:150px' XXmultiple=no size=12 class=ssw_itemList >";
    if (args[2]) {
        //
    }
    //var full = {}
    var disps = {}
    for (var i in list) {
        var line = list[i];
        if (args[3] != null) {
            if (!args[3].run(line)) {
                continue;
            }
        }
        y += "<option>";
        //var fl = buildStringFromFields(line,false,false);
        var nm = line[field];
        //full[nm] = buildStringFromFields(line,true,true);
        disps[nm] = line['_display'];
        //if (all) {
          //  y += fl;
        //} else {
        y += nm;
        //}
        y += "</option>";
    }
    y += "</select>";
    $(args[0]).html(y);
    //listen(obj2,full);
    listen2(args[1],disps);
}

function listEntities(typ,view,filter) {
    var obj1 = '.ssw_entityBlock#1';
    var obj2 = '.ssw_entityBlock#2';
    var args = new Array();
    args.push(obj1, obj2, view=="form", filter);
    processEntitiesFromServer(typ,view,showNamesAsSelect,args,true);
}

function listTeamsByUser(view,id) {
    var filt = {
        uid:id,
        run: function(ent) {
            if (ent._id == null) {
                return true;
            }
            return (ent._manager[0] == this.uid);
        }
    };
    listEntities("TeamE",view,filt);
}

function setSessionAttr(k, v) {
    // Need sync call here because the whole point is to 
    // side-effect the session. 
    var r = false; 
    $.ajax({ 
         async: false, 
         url: "Ajx?op=sessattr&key="+k+"&val="+v+"", 
         dataType: "json", 
         success: function(data) {
             if (data == true) {                   
                 r = true; 
             }
         }
    });
    return r; 
}

/* m m m m XXXX
function getEntitiesFromServer(typ,view) {    
    var list = [];
    var r = $.getJSON("Ajx?", {op:view, type:typ}, function(data) {
        for(i=0; i<data.length; i++) {
            e = data[i];
            s = $.param(e);
            var line = {};
            $.each(e, function(i, val) {
                line[i] = val;
            });            
            list.push(line);
        }
    });
    r.complete(function(){ });
}    */

function processEntitiesFromServer(typ,view,handler,args,async) {
    var list = [];
    $.ajaxSetup({async:async});
    $.getJSON("Ajx?", {op:view, type:typ}, function(data) {
        for(i=0; i<data.length; i++) {
            e = data[i];
            s = $.param(e);
            var line = {};
            $.each(e, function(i, val) {
                line[i] = val;
            });            
            list.push(line);
        }
        if (handler != null) {
            handler(list,args);  
        }
    });
    $.ajaxSetup({async:true});
    return list;
}

function menuTitle(index) {
    switch(index) {
        case 0:
            return "Team";
        case 1:
            return "Field";
        case 2:
            return "Day";
        case 3:
            return "Time";
        default:
            return "??";
    }
}

function listen2(obj2, disps) {
    $('body').on("change", ".ssw_itemList", function() {
        var ent = disps[$(this).val()];
        var y = '<p>'+ ent +'</p>';
        $(obj2).html(y);
        //
        // XXX disableForm();
    });
}

function sswAlert(elm,text) {
    $("#"+elm).html('<div id="'+elm+'" ><p><span XXclass="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 50px 0;"></span></p><p id="'+elm+'_text">Some text</p></div>');
    $("#"+elm+"_text").html(text);
    $("#"+elm).dialog({
        autoOpen: true,
        modal: true,
        title: "Attention!",
        buttons: {
            Close: function() {
                $( this ).dialog("close");
            }
        }
    });
    return false;
}

/* mm m XXXX m m m m
function confirmSubmit() {
    
}*/

function submitButtonDiv(text) {
    return '<div id=ssw_submit>'+submitButton(text)+'</div>';
}

function submitButton(text) {
    //text = "Submit";
    var y = '<button onclick="return validateForm(this)" type=button id=ssw_submit >'+text+'</button>';
    return y;
}

function listenToChange() {
    listenToMenuChange("Ajx");
    $('body').on("change keyup", function() {
        var txt = $('div#ssw_submit')[0].firstChild.innerText;
        $('div#ssw_submit').html(submitButton(txt));
    });
}

function disableSubmit() {
    $('div#ssw_submit').html(
        '<button type=button disabled=disabled >...Please wait...</button>');
}
